package com.farm.wsch.index;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.DocStats;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.farm.wsch.index.impl.WschIndexServerImpl;
import com.farm.wsch.index.impl.WschSearchServerImpl;
import com.farm.wsch.index.pojo.IndexConfig;

/**
 * 索引服务工厂类
 * 
 * @author macpl
 *
 */
public class WschIndexFactory {

	/**
	 * 获得一个索引创建器
	 * 
	 * @return
	 * @throws IOException
	 */
	public static WschIndexServerInter getIndexServer(IndexConfig config) throws IOException {
		return new WschIndexServerImpl(config);
	}

	public static WschSearchServerInter getSearchServer(IndexConfig config) throws IOException {
		return new WschSearchServerImpl(config);
	}

	public static Map<String, Object> getStats(IndexConfig config) throws IOException {
		synchronized (WschIndexServerInter.class) {
			Map<String, Object> map = new HashMap<String, Object>();
			Directory directory = FSDirectory.open(Paths.get(config.getIndexDir().getPath()));
			Analyzer analyzer = new IKAnalyzer();
			IndexWriterConfig iwconfig = new IndexWriterConfig(analyzer);
			IndexWriter indexWriter = null;
			map.put("PATH", config.getIndexDir().getPath());
			try {
				indexWriter = new IndexWriter(directory, iwconfig);
				DocStats stats = indexWriter.getDocStats();
				map.put("MAXDOC", stats.maxDoc);
				map.put("NUMDOCS", stats.numDocs);
			} finally {
				if (indexWriter != null)
					indexWriter.close();
			}
			DirectoryReader indexReader = null;
			try {
				indexReader = DirectoryReader.open(directory);
				map.put("NUMDOCS", indexReader.numDocs());
				map.put("VERSION", indexReader.getVersion());

			} finally {
				if (indexReader != null)
					indexReader.close();
			}
			return map;
		}
	}
}
